package asa;

import java.util.List;

import forum.ForumFactory;
import forum.ForumPost;

import ml.DataModel;
import ner.NER;
import parser.ParserAnnotation;

public class Pipeline extends Thread {

	private NER ner;
	private ForumFactory fac;
	private PostBucket inBucket;
	private PostBucket outBucket;
	private DataModel dm;

	public Pipeline(DataModel sdm, NER ner, ForumFactory fac,
			PostBucket inBucket, PostBucket outBucket) {
		super("Pipeline");
		this.dm = sdm;
		this.ner = ner;
		this.fac = fac;
		this.inBucket = inBucket;
		this.outBucket = outBucket;
	}

	public void run() {
		while (!inBucket.finished() || inBucket.size() > 0) {
			List<ForumPost> posts;
			try {
				posts = inBucket.getPost();
				if (posts == null)
					break;
				process(posts);
				outBucket.addPost(posts);
			} catch (InterruptedException ie) {
				break;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		outBucket.finish();
		System.err.println("Pipeline finished.");
	}

	private void process(List<ForumPost> ft) throws Exception {
		long start;
		long end;
		long timeClassify = 0;
		long timeNer = 0;
		for (ForumPost fp : ft) {
			ParserAnnotation pa = fp.getParserAnnotation();
			pa.parse();
			if (!pa.getSkipSentDetection()) {
				List<String> sents = pa.getSentences();
				if (pa.getNbrSentences() == 0)
					continue;
				for (String sent : sents)
					fac.makeSent(sent, fp);
			}

			start = System.currentTimeMillis();
			dm.classify(fp);
			end = System.currentTimeMillis();
			timeClassify += end - start;

			start = System.currentTimeMillis();
			ner.items(fp);
			end = System.currentTimeMillis();
			timeNer += end - start;
		}
	}
}